<template>
  <div class="unit-management">
    <!-- 顶部标题和搜索 -->
    <div class="header">
      <h2>计量单位</h2>
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入单位名称"
          clearable
          class="search-input"
        />
        <el-button type="primary">查询</el-button>
      </div>
    </div>

    <!-- 主内容区 - 左右结构 -->
    <div class="content-wrapper">
      <!-- 左侧 - 单计量单位（超过5条显示滚动条） -->
      <div class="unit-section single-unit-section">
        <div class="section-header">
          <h3>单计量单位</h3>
          <el-button type="primary" @click="showAddSingleUnitDialog">新增</el-button>
        </div>
        <div class="table-container" :class="{ 'has-scroll': singleUnits.length > 5 }">
          <el-table :data="singleUnits" border style="width: 100%">
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button type="text" size="small" @click="showEditSingleUnitDialog(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleDeleteSingleUnit(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" />
          </el-table>
        </div>
      </div>

      <!-- 右侧 - 多计量单位（超过5条显示滚动条） -->
      <div class="unit-section multi-unit-section">
        <div class="section-header">
          <h3>多计量单位</h3>
          <div>
            <el-button type="primary" @click="showAddMultiUnitDialog">新增</el-button>
          </div>
        </div>
        <div class="table-container" :class="{ 'has-scroll': multiUnits.length > 5 }">
          <el-table :data="multiUnits" border style="width: 100%">
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button type="text" size="small" @click="showEditMultiUnitDialog(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleDeleteMultiUnit(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" />
          </el-table>
        </div>
      </div>
    </div>

    <!-- 单计量单位弹窗 - 完全匹配第1张图片 -->
    <el-dialog
      :title="singleUnitDialogTitle"
      v-model="showSingleUnitDialog"
      width="500px"
    >
      <el-form :model="singleUnitForm" :rules="singleUnitRules" ref="singleUnitFormRef">
        <el-form-item label="名称" prop="name" required>
          <el-input v-model="singleUnitForm.name" placeholder="请输入单位名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSingleUnitDialog = false">关闭</el-button>
          <el-button type="primary" @click="handleSingleUnitSubmit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 多计量单位弹窗 - 完全匹配第2张图片 -->
    <el-dialog
      :title="multiUnitDialogTitle"
      v-model="showMultiUnitDialog"
      width="600px"
    >
      <el-form :model="multiUnitForm" :rules="multiUnitRules" ref="multiUnitFormRef">
        <el-form-item label="多单位名称：" prop="displayName">
          <el-input v-model="multiUnitForm.displayName" placeholder="例如：包,盒(1:6)"></el-input>
        </el-form-item>
        
        <el-form-item label="基本单位：" prop="baseUnit" required>
          <el-input v-model="multiUnitForm.baseUnit" placeholder="例如：包"></el-input>
          <div class="form-tip">基本单位应为最小度量单位</div>
        </el-form-item>
        
        <div v-for="(unit, index) in multiUnitForm.additionalUnits" :key="index" class="additional-unit">
          <el-form-item 
            :label="`副单位${index + 1}：`" 
            :prop="`additionalUnits.${index}.name`" 
            :rules="{ required: true, message: '请输入副单位名称', trigger: 'blur' }"
          >
            <el-input v-model="unit.name" placeholder="例如：盒" style="width: 150px"></el-input>
            <span class="equal-sign">=</span>
            <el-input-number v-model="unit.ratio" :min="1" :step="1" style="width: 100px"></el-input-number>
            <span class="unit-name">{{ multiUnitForm.baseUnit }}</span>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="text" @click="addAdditionalUnit">增加单位</el-button>
          <div>
            <el-button @click="showMultiUnitDialog = false">关闭</el-button>
            <el-button type="primary" @click="handleMultiUnitSubmit">保存</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UnitManagement',
  setup() {
    const searchQuery = ref('')
    
    // 单计量单位数据
    const singleUnits = reactive([
      { id: 1, name: '瓶' },
      { id: 2, name: '包' },
      { id: 3, name: '个' },
      { id: 4, name: '袋' },
    ])
    
    // 多计量单位数据
    const multiUnits = reactive([
      { 
        id: 1, 
        name: '包,盒(1:6)',
        baseUnit: '包',
        additionalUnits: [
          { name: '盒', ratio: 6 }
        ]
      },
      { 
        id: 2, 
        name: '包,个(1:12)',
        baseUnit: '包',
        additionalUnits: [
          { name: '个', ratio: 12 }
        ]
      },
      { 
        id: 3, 
        name: '瓶,件,个(1:6:24)',
        baseUnit: '瓶',
        additionalUnits: [
          { name: '件', ratio: 6 },
          { name: '个', ratio: 24 }
        ]
      },
      { 
        id: 4, 
        name: '瓶,个(1:12)',
        baseUnit: '瓶',
        additionalUnits: [
          { name: '个', ratio: 12 }
        ]
      }
    ])
    
    // 单计量单位弹窗相关
    const showSingleUnitDialog = ref(false)
    const singleUnitDialogTitle = ref('新增单计量单位')
    const singleUnitForm = reactive({
      id: null,
      name: ''
    })
    const singleUnitRules = reactive({
      name: [
        { required: true, message: '请输入单位名称', trigger: 'blur' }
      ]
    })
    const singleUnitFormRef = ref(null)
    
    // 多计量单位弹窗相关
    const showMultiUnitDialog = ref(false)
    const multiUnitDialogTitle = ref('新增多计量单位')
    const multiUnitForm = reactive({
      id: null,
      displayName: '',
      baseUnit: '',
      additionalUnits: [
        { name: '', ratio: 1 }
      ]
    })
    const multiUnitRules = reactive({
      displayName: [
        { required: true, message: '请输入多单位名称', trigger: 'blur' }
      ],
      baseUnit: [
        { required: true, message: '请输入基本单位', trigger: 'blur' }
      ]
    })
    const multiUnitFormRef = ref(null)
    
    // 单计量单位相关方法
    const showAddSingleUnitDialog = () => {
      singleUnitDialogTitle.value = '新增单计量单位'
      singleUnitForm.id = null
      singleUnitForm.name = ''
      showSingleUnitDialog.value = true
    }
    
    const showEditSingleUnitDialog = (unit) => {
      singleUnitDialogTitle.value = '修改单计量单位'
      singleUnitForm.id = unit.id
      singleUnitForm.name = unit.name
      showSingleUnitDialog.value = true
    }
    
    const handleSingleUnitSubmit = () => {
      singleUnitFormRef.value.validate(valid => {
        if (valid) {
          if (singleUnitForm.id) {
            // 更新现有单位
            const index = singleUnits.findIndex(u => u.id === singleUnitForm.id)
            if (index !== -1) {
              singleUnits[index].name = singleUnitForm.name
              ElMessage.success('修改成功')
            }
          } else {
            // 新增单位
            const newId = Math.max(...singleUnits.map(u => u.id), 0) + 1
            singleUnits.push({
              id: newId,
              name: singleUnitForm.name
            })
            ElMessage.success('添加成功')
          }
          showSingleUnitDialog.value = false
        }
      })
    }
    
    const handleDeleteSingleUnit = (unit) => {
      ElMessageBox.confirm('确定要删除该计量单位吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = singleUnits.findIndex(u => u.id === unit.id)
        if (index !== -1) {
          singleUnits.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 多计量单位相关方法
    const showAddMultiUnitDialog = () => {
      multiUnitDialogTitle.value = '新增多计量单位'
      multiUnitForm.id = null
      multiUnitForm.displayName = ''
      multiUnitForm.baseUnit = ''
      multiUnitForm.additionalUnits = [{ name: '', ratio: 1 }]
      showMultiUnitDialog.value = true
    }
    
    const showEditMultiUnitDialog = (unit) => {
      multiUnitDialogTitle.value = '修改多计量单位'
      multiUnitForm.id = unit.id
      multiUnitForm.displayName = unit.name
      multiUnitForm.baseUnit = unit.baseUnit
      multiUnitForm.additionalUnits = unit.additionalUnits.map(u => ({ ...u }))
      showMultiUnitDialog.value = true
    }
    
    const addAdditionalUnit = () => {
      multiUnitForm.additionalUnits.push({
        name: '',
        ratio: 1
      })
    }
    
    const handleMultiUnitSubmit = () => {
      multiUnitFormRef.value.validate(valid => {
        if (valid) {
          // 生成显示名称
          const ratios = [1, ...multiUnitForm.additionalUnits.map(u => u.ratio)]
          const ratioStr = ratios.join(':')
          
          const unitNames = [
            multiUnitForm.baseUnit,
            ...multiUnitForm.additionalUnits.map(u => u.name)
          ]
          
          const displayName = `${unitNames.join(',')}(${ratioStr})`
          
          const newUnit = {
            id: multiUnitForm.id || Math.max(...multiUnits.map(u => u.id), 0) + 1,
            name: displayName,
            baseUnit: multiUnitForm.baseUnit,
            additionalUnits: multiUnitForm.additionalUnits.map(u => ({ ...u }))
          }
          
          if (multiUnitForm.id) {
            // 更新现有单位
            const index = multiUnits.findIndex(u => u.id === multiUnitForm.id)
            if (index !== -1) {
              multiUnits.splice(index, 1, newUnit)
              ElMessage.success('修改成功')
            }
          } else {
            // 新增单位
            multiUnits.push(newUnit)
            ElMessage.success('添加成功')
          }
          
          showMultiUnitDialog.value = false
        }
      })
    }
    
    const handleDeleteMultiUnit = (unit) => {
      ElMessageBox.confirm('确定要删除该计量单位吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = multiUnits.findIndex(u => u.id === unit.id)
        if (index !== -1) {
          multiUnits.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    return {
      searchQuery,
      singleUnits,
      multiUnits,
      showSingleUnitDialog,
      singleUnitDialogTitle,
      singleUnitForm,
      singleUnitRules,
      singleUnitFormRef,
      showMultiUnitDialog,
      multiUnitDialogTitle,
      multiUnitForm,
      multiUnitRules,
      multiUnitFormRef,
      showAddSingleUnitDialog,
      showEditSingleUnitDialog,
      handleSingleUnitSubmit,
      handleDeleteSingleUnit,
      showAddMultiUnitDialog,
      showEditMultiUnitDialog,
      addAdditionalUnit,
      handleMultiUnitSubmit,
      handleDeleteMultiUnit
    }
  }
}
</script>

<style scoped>
.unit-management {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.search-bar {
  display: flex;
  align-items: center;
}

.search-input {
  width: 250px;
  margin-right: 10px;
}

/* 左右结构布局 */
.content-wrapper {
  flex: 1;
  display: flex;
  gap: 20px;
  overflow: hidden;
}

.unit-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.single-unit-section {
  flex: 1;
}

.multi-unit-section {
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

/* 表格容器 - 超过5条显示滚动条 */
.table-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.table-container.has-scroll {
  overflow-y: auto;
}

/* 设置表格行高和最大显示行数 */
.el-table {
  width: 100%;
}

.el-table__body-wrapper {
  max-height: calc(5 * 48px); /* 5行数据的高度 */
  overflow-y: hidden;
}

.has-scroll .el-table__body-wrapper {
  max-height: none;
}

.help-link {
  margin-right: 15px;
  color: #409EFF;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.additional-unit {
  margin-bottom: 15px;
}

.equal-sign {
  margin: 0 10px;
  color: #606266;
}

.unit-name {
  margin-left: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>